package igloo.util;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class EventSupport<L> implements IEventRaiser<L>
{
    protected List<L> mListeners;

    public List<L> getListeners()
    {
        if(mListeners == null)
            return Collections.emptyList();

        return Collections.unmodifiableList(mListeners);
    }

    /**
     * Adds the given listener to the listeners list using a WEAK REFERENCE.
     * 
     * Since a weak reference is used anonymous inner classes should not be
     * used, as they will have no strong references to them and be almost
     * immediately garbage collected.
     */
    public void addListener(L listener)
    {
        if(listener == null)
            return;

        if(mListeners == null)
            mListeners = new CopyOnWriteArrayList<L>();
        else if(mListeners.contains(listener))
            return;

        mListeners.add(listener);
    }

    public void removeListener(L listener)
    {
        if(mListeners == null)
            return;

        mListeners.remove(listener);

        if(mListeners.isEmpty())
            mListeners = null;
    }

    public void clear()
    {
        if(mListeners == null)
            return;

        mListeners.clear();
        mListeners = null;
    }
}
